import 'package:flutter/material.dart';
import 'package:manual/theme/loading_ovaerlay_theme.dart';

class Toast {
  /// 显示 Toast 消息
  static void show(
    BuildContext context,
    String message, {
    /// Toast 显示的位置，默认居中
    ToastPosition position = ToastPosition.center,

    /// 文本颜色，可选
    Color? textColor,

    /// 持续时间，默认 2 秒
    Duration duration = const Duration(seconds: 2),
  }) {
    final overlay = Overlay.of(context);
    // 获取主题中的 LoadingOverlay 样式
    final theme = Theme.of(context).extension<LoadingOverlayTheme>()!;
    final backgroundColor = theme.backgroundColor;
    final loadingColor = theme.loadingColor;

    // 创建 OverlayEntry
    OverlayEntry overlayEntry = OverlayEntry(
      builder: (context) {
        // 获取位置
        double? top;
        double? bottom;
        switch (position) {
          case ToastPosition.top:
            top = MediaQuery.of(context).size.height * 0.2;
            break;
          case ToastPosition.bottom:
            bottom = MediaQuery.of(context).size.height * 0.2;
            break;
          case ToastPosition.center:
          default:
            top = null; // 居中时不设置 top 和 bottom
            bottom = null;
        }

        return Stack(
          children: [
            Positioned.fill(
              child: IgnorePointer(
                ignoring: true, // 禁止点击事件穿透
                child: Container(
                  color: Colors.transparent, // 可选：添加透明背景防止视觉干扰
                ),
              ),
            ),
            Align(
              alignment: position == ToastPosition.top
                  ? Alignment.topCenter
                  : position == ToastPosition.bottom
                      ? Alignment.bottomCenter
                      : Alignment.center,
              child: Padding(
                padding: EdgeInsets.only(
                  top: top ?? 0,
                  bottom: bottom ?? 0,
                ),
                child: Material(
                  color: Colors.transparent,
                  child: Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    decoration: BoxDecoration(
                      color: backgroundColor,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      message,
                      style: TextStyle(
                        color: loadingColor,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        );
      },
    );

    // 插入 Overlay
    overlay.insert(overlayEntry);

    // 自动移除
    Future.delayed(duration).then((value) => overlayEntry.remove());
  }
}

/// Toast 位置的枚举
enum ToastPosition {
  top,
  center,
  bottom,
}
